﻿using IdentityManagerServiceApi.Data;
using SharedClassLibrary;
using SharedClassLibrary.Contracts;
using SharedClassLibrary.DTOs;

namespace IdentityManagerServiceApi
{
    public class UserService : IUserService
    {
        private readonly AppDbContext context;
        private readonly IConfiguration configuration;

        public UserService(AppDbContext context, IConfiguration configuration)
        {
            this.context = context;
            this.configuration = configuration;
        }

        public Task<GeneralResponse> CreateAccountAsync(UserDTO userDTO)
        {
            var user = new User
            {
                UserName = userDTO.UserName,
                Password = userDTO.Password,
                IsDeleted = false,
                Version = 0
            };
            context.Users.Add(user);
            context.SaveChanges();
            return Task.FromResult(new GeneralResponse { Flag = true, Message = "success" });
        }

        public Task<LoginResponse> LoginAsync(LoginDTO loginDTO)
        {
            var user = context.Users.FirstOrDefault(predicate => predicate.UserName == loginDTO.UserName);
            if (user == null)
                return Task.FromResult(new LoginResponse { Flag = false });

            UserSession userSession = new UserSession(user.Id, user.UserName, "admin");
            return Task.FromResult(new LoginResponse { Flag = true, Token = GenerateToken(userSession), Message = "success" });
        }

        private string GenerateToken(UserSession session)
        {
            var signingKey = configuration["Jwt:SigningKey"];
            var issuer = configuration["Jwt:Issuer"];
            var audience = configuration["Jwt:Audience"];
            var token = Generics.GenerateToken(session, signingKey, issuer, audience);
            return token;
        }
    }
}
